package com.aplikata.evok.email;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aplikata.bo.AplikataEmail;
import com.aplikata.bo.Domain;
import com.aplikata.bo.User;
import com.aplikata.bo.UserReference;
import com.aplikata.constants.Constants;
import com.aplikata.evok.bo.DoctorSchedule;
import com.aplikata.evok.bo.PatientTherapyComment;
import com.aplikata.evok.constants.EvokConstants;
import com.aplikata.evok.constants.EvokEmailConstants;
import com.aplikata.service.PublicService;
import com.aplikata.util.AplikataEmailUtil;
import com.aplikata.util.FacesUtil;
import com.aplikata.util.ServiceFinder;
import com.aplikata.util.StringUtil;
import com.aplikata.util.YunDateUtil;

public class EvokEmailUtil {
	private static Log log = LogFactory.getLog(EvokEmailUtil.class);

	public static String getEmailContent(String msgContentKey, Object[] obj, Domain domain) {

		String appname = FacesUtil.getEmailMessage(EvokEmailConstants.EVOK_APP, new Object[] { domain.getName() });
		String content = FacesUtil.getEmailMessage(msgContentKey, obj);
		String link = "LINK: " + FacesUtil.getEmailMessage(Constants.EMAIL_LOGIN_URL);
		String contact = FacesUtil.getEmailMessage(EvokEmailConstants.DOMAIN_CONTACT, new Object[] { domain.getName(),
				domain.getStreet(), domain.getCity().getName(), domain.getTel(), domain.getFax(), domain.getEmail() });

		return appname + "<br/>" + content + "<br/>" + link + "<br/><p/>" + contact;
	}

	@SuppressWarnings("unchecked")
	public static void sendReservationEmail(Long patientId, DoctorSchedule schedule, Integer status) {
		if (EvokConstants.DOC_RESERVATION_STATUS_CANCEL != schedule.getStatus().intValue())
			return;

		PublicService publicService = (PublicService) ServiceFinder.findBeanForWeb("publicService");
		String sql = " SELECT u.*, uf.*  FROM _user_reference uf, _user u , evk_patient p "
				+ " where uf.user_id=u.id and uf.send_email = true and (u.email is not null and u.email != '') "
				+ " and p.user_id = u.id and p.id =" + patientId;
		List<Object[]> testlist = publicService.getSqlQuery(sql).addEntity("u", User.class)
				.addEntity("uf", UserReference.class).list();
		if (testlist == null || testlist.isEmpty())
			return;

		Object[] objects = (Object[]) testlist.get(0);
		User patientUser = (User) objects[0];
		UserReference patientReference = (UserReference) objects[1];

		if (objects[1] != null) {
			List<String> list = new ArrayList<String>();
			list.add(patientUser.getEmail());
			UserReference doctorReference = schedule.getDoctor().getUserReference();

			String doctorName = doctorReference.getSurname() + " " + doctorReference.getName();
			String patientName = patientReference.getSurname() + " " + patientReference.getName();
			String statusString = FacesUtil.getEnumLabel("ReservationStatus", status);

			String contentString = EvokEmailUtil.getEmailContent(EvokEmailConstants.RESERVATION_CONTENT, new Object[] {
					doctorName, patientName, YunDateUtil.formatDate(schedule.getTimeFrom(), "dd/MM/yyyy HH:mm"),
					statusString }, FacesUtil.getDomainFromSession());

			AplikataEmail aemail = null;
			try {
				aemail = AplikataEmailUtil.prepareAplikataEmail(FacesUtil.getEmailMessage(
						EvokEmailConstants.RESERVATION_SUBJECT, new Object[] { statusString }), contentString, list);
				aemail.getEmail().send();
			} catch (Exception e) {
				log.error("send reservation email from doctor  failed!", e);
				try {
					if (aemail != null)
						publicService.merge(aemail);
				} catch (Exception e1) {
					log.error("save reservation email from doctor failed!", e1);
				}
			}
		}
	}

	public static void sendCommentEmail(PatientTherapyComment comment) {
		String sqlString = "SELECT u.email FROM evk_patient_therapy_comment c, _user u, _user_reference uf "
				+ " where c.receiver_id = u.id and u.id = uf.user_id and (u.email is not null and u.email !='')"
				+ " and uf.send_email = true and c.id=" + comment.getId();

		PublicService publicService = (PublicService) ServiceFinder.findBeanForWeb("publicService");
		String email = (String) publicService.findSingleBySql(sqlString);

		if (StringUtil.isStrEmpty(email))
			return;

		List<String> list = new ArrayList<String>();
		list.add(email);

		String senderName = comment.getSender().getUserReference().getSurname() + " "
				+ comment.getSender().getUserReference().getName();

		String contentString = EvokEmailUtil.getEmailContent(EvokEmailConstants.COMMENT_CONTENT, new Object[] {
				YunDateUtil.formatDate(comment.getPatientTherapy().getStartDate(), "dd/MM/yyyy"),
				senderName, comment.getMessage() }, FacesUtil.getDomainFromSession());

		AplikataEmail aemail = null;
		try {
			aemail = AplikataEmailUtil.prepareAplikataEmail(
					FacesUtil.getEmailMessage(EvokEmailConstants.COMMENT_SUBJECT), contentString, list);
			aemail.getEmail().send();
		} catch (Exception e) {
			log.error("send comment email  failed!", e);
			try {
				if (aemail != null)
					publicService.merge(aemail);
			} catch (Exception e1) {
				log.error("save comment email failed!", e1);
			}
		}
	}
}
